package com.zhengxyou.jetpackdemo.room.dao;

import android.database.Cursor;

import com.zhengxyou.jetpackdemo.room.entity.NameTuple;
import com.zhengxyou.jetpackdemo.room.entity.User;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import androidx.lifecycle.LiveData;
import androidx.paging.DataSource;
import androidx.room.Dao;
import androidx.room.Delete;
import androidx.room.Insert;
import androidx.room.OnConflictStrategy;
import androidx.room.Query;
import androidx.room.Update;
import io.reactivex.Completable;
import io.reactivex.Flowable;
import io.reactivex.Single;

@Dao
public interface UserDao {
    @Query("SELECT * FROM user")
    List<User> getAll();

    @Query("SELECT * FROM user WHERE id IN (:ids)")
    List<User> loadAllByIds(int[] ids);

    @Query("SELECT * FROM user WHERE post_code IN (:regions)")
    List<User> loadUserFromRegions(List<Integer> regions);

    @Query("SELECT * FROM user WHERE first_name LIKE :first AND last_name LIKE :last LIMIT 1")
    User findByName(String first, String last);

    @Insert
    void insertAll(User... users);

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    void insertUser(User user);

    @Delete
    void delete(User user);

    @Update
    void update(User user);

    @Query("SELECT first_name ,last_name FROM user")
    List<NameTuple> loadFullName();

    @Query("SELECT * FROM user")
    LiveData<List<User>> loadUserSync();

    @Query("SELECT *FROM user WHERE id=:id LIMIT 1")
    Flowable<User> loadUserById(int id);

//    @Insert
//    Maybe<Integer> insertLargeNumberOfUsers(List<User> users);

    //确保操作成功完成。
    @Insert
    Completable insertLargeNumberOfUsers(User... users);

    //发射从数据库中删除的用户数。
    //总是发射至少一个用户。
    @Delete
    Single<Integer> deleteUsers(List<User> users);

    //不建议使用Cursor
    @Query("SELECT * FROM user WHERE id>=:id LIMIT 5")
    Cursor loadRawUserThanId(int id);

    @Query("SELECT * FROM user WHERE birthday BETWEEN :from AND :to")
    List<User> findUserBornBetweenDates(Date from, Date to);

    @Query("SELECT first_name,last_name FROM user LIMIT 15 OFFSET :currentPage*15")
    List<NameTuple> getUserByPage(int currentPage);

    @Query("SELECT * FROM user ORDER BY id DESC")
    DataSource.Factory<Integer, User> usersById();
}
